//
//  CreditNetHelper.m
//  

#import "CreditNetHelper.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "CreaditNetManager.h"

#import "NetDataCacheManager.h"

@interface HttpRequestSerializer : AFHTTPRequestSerializer

@end



@implementation HttpRequestSerializer

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(id)parameters
                                     error:(NSError *__autoreleasing *)error {
    NSMutableURLRequest *request = [super requestWithMethod:method URLString:URLString parameters:parameters error:error];

    request.timeoutInterval = 15.0;
    
    return request;
}

@end


@implementation CreditNetHelper

+ (void)moniterNetworking{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        [CreaditNetManager sharedCreaditNetManager].isAvailable = status ? YES : NO;
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}


+ (void)configHttpManager{
    
    AFHTTPSessionManager * manager = [self manager];
    
    manager.requestSerializer = [[HttpRequestSerializer alloc] init];
}

+ (AFHTTPSessionManager *)manager{
    
    static dispatch_once_t onceToken;
    static AFHTTPSessionManager *manager;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        
        NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
        [NSURLCache setSharedURLCache:URLCache];
    });
    return manager;
}

+ (NSURLSessionDataTask *)getWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    return [self requestWithPath:path params:params success:success failure:failure method:kGetMethod];
}

+ (NSURLSessionDataTask *)postWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    return [self requestWithPath:path params:params success:success failure:failure method:kPostMethod];
}

+ (NSURLSessionDataTask *)requestWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure method:(NSString *)method{
    
    AFHTTPSessionManager *manager = [self manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 15.0f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"text/plain",@"image/png",@"application/octet-stream",@"text/json",@"text/x-vcard",nil];
    void (^block)(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject) = ^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject) {
   
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        if (isDictionary(responseObject) && [responseObject[@"dim"] integerValue] == kExpireCode) {
            success(nil);
            [CreditServerHelper tokenLoseToLogoutController:YES];
        }
        else{
            [NetDataCacheManager saveCacheWithObject:responseObject forURLKey:path completion:nil];
            success(responseObject);
        }
    
    };

    if(![CreaditNetManager sharedCreaditNetManager].isAvailable) {
       
        NSString *responseCacheObject=[NetDataCacheManager readCacheWithURLKey:path];
        if(responseCacheObject){
           
            success(responseCacheObject);
            
            return nil;
    
        }
    }
    
    NSMutableDictionary *mDic = @{
        @"token":esString([CurrentUser mine].sessionKey),
    }.mutableCopy;
    
    NSURLSessionDataTask *op;
    if ([method isEqualToString:kPostMethod]) {
        op = [manager POST:path parameters:params headers:mDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(task, responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(error);
            DLog(@"error=====%@",error);
        }];
        
    }else{
        op = [manager GET:path parameters:params headers:mDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(error);
            DLog(@"error=====%@",error);
        }];
        
    }

    
    return op;
}



@end
